-- 因为单主的需求不明确，导致该组件的代码写的有点乱，现在这个组件给魔刀和剪刀都有用

local QianrenGrowth = Class(function(self, inst)
    self.inst = inst
    self.level = 0
    self.exp = 0
    self.exp_per_level = 100
    self.base_damage = 51
    self.max_level = 10 -- 新增：最高等级
    self.add_damage = 0

    -- 初始化武器伤害
    inst:DoTaskInTime(0, function()
        self:UpdateWeaponDamage()
    end)

    inst:AddTag("assn_growth")
end)

-- 设置最高等级
function QianrenGrowth:SetMaxLevel(max_level)
    self.max_level = max_level
end

-- 增加经验，并处理升级，最多升级到 self.max_level
function QianrenGrowth:AddExp(amount)
    if self.level >= self.max_level then
        -- 已到达最高等级，不再增加经验
        return
    end

    self.exp = self.exp + amount
    -- 循环升级，直到经验不够或到达最高等级
    while self.exp >= self.exp_per_level and self.level < self.max_level do
        self.exp = self.exp - self.exp_per_level
        self.level = self.level + 1
        self:UpdateWeaponDamage()

        -- 如果正好升到最高等级，清空多余经验
        if self.level == self.max_level then
            self.exp = 0
            break
        end
    end
    if self.inst.components.talker ~= nil then
        self.inst.components.talker:Say("exp:" .. self.exp .. "\n" .. "level:" .. self.level)
    end
end

-- 增减等级（正数增、负数减），并保持在 [0, max_level] 范围内
function QianrenGrowth:DeltaLevel(amount)
    if type(amount) == "number" and amount ~= 0 then
        self.level = math.clamp and math.clamp(self.level + amount, 0, self.max_level)
            or ((self.level + amount) < 0 and 0
                or ((self.level + amount) > self.max_level and self.max_level
                    or (self.level + amount)))
        self:UpdateWeaponDamage()
    end
end

-- 每次等级或经验变化，都调用它来更新伤害
function QianrenGrowth:UpdateWeaponDamage()
    if self.inst.components.weapon then
        local bonus = self.level -- 每级加 1 伤害
        if self.inst.components.projectile ~= nil then
            self.inst.components.weapon:SetDamage(self.inst.assn_base_damage1 + bonus)
        else
            self.inst.components.weapon:SetDamage(self.inst.assn_base_damage + bonus + self.add_damage)
        end
    end
end

function QianrenGrowth:OnSave()
    return {
        level      = self.level,
        exp        = self.exp,
        add_damage = self.add_damage,
    }
end

function QianrenGrowth:OnLoad(data)
    if data then
        self.level      = data.level or 0
        self.exp        = data.exp or 0
        self.add_damage = data.add_damage or 0
        -- 加载时也要修正：不超过最高等级，经验在 [0, exp_per_level) 范围
        if self.level > self.max_level then
            self.level = self.max_level
            self.exp   = 0
        end
        if self.exp >= self.exp_per_level then
            self.exp = self.exp % self.exp_per_level
        end
        self:UpdateWeaponDamage()
    end
end

return QianrenGrowth
